package pub.tbc.atps.collector;

import lombok.extern.slf4j.Slf4j;
import pub.tbc.atps.collector.receiver.Receiver;
import pub.tbc.atps.collector.receiver.redis.RedisReceiver;
import pub.tbc.atps.config.PropConfig;
import pub.tbc.atps.process.HandlerInvoker;
import pub.tbc.atps.task.RestTask;
import pub.tbc.toolkit.Objs;

import java.util.concurrent.TimeUnit;

/**
 * @author tbc on 2016/11/29 13:03:09.
 */
@Slf4j
public class Collectors {

    private Receiver receiver = new RedisReceiver();

    private int SLEEP_TIME = PropConfig.getInt("task.sleep.time");

    private void start() {
        while (true) {
            log.info("开始从队列提取任务...");
            RestTask task = receiver.getTask();
            // 判断，没任务就休息一会儿
            if (Objs.isEmpty(task)) {
                log.info("当前无任务，休眠[" + SLEEP_TIME + "]毫秒");
                try {
                    TimeUnit.MILLISECONDS.sleep(SLEEP_TIME);
                    continue;
                } catch (InterruptedException e) {
                    log.error("Collectors - InterruptedException: {}", e.getMessage());
                    System.exit(1);
                }
            }
            // 有任务，调用处理器
            log.info("获取任务成功，内容：{}，开始处理...", task);
            HandlerInvoker.process(task);
        }
    }

    public static void monitor() {
        Collectors processor = new Collectors();
        processor.start();
    }
}
